<?php
/**
 * CK框架 验证码类
 * @author wujibing<283109896@qq.com>
 * @version   1.0
 * @category   CkFrameWork
 * @package  CkFrameWork
 * @subpackage lib
 */
class checkCode
{
	/**
	 * 定义图片的宽度
	 * @var int
	 */
	private static $width = 70;
	/**
	 * 定义图片的高度
	 * @var int
	 */
	private static $height = 31;
	
	/**
	 * 设置图片的宽度
	 * @param int $width
	 */
	public static function setWidth($width)
	{
		$width = (int)$width;
		if($width <= 0)
		{
			return false;
		}
		self::$width = $width;
	}
	/**
	 * 设置图片的高度
	 * @param int $width
	 */
	public static function setHeight($height)
	{
		$height = (int)$height;
		if($height <= 0)
		{
			return false;
		}
		self::$height = $height;
	}
	/**
	 * 
	 * 获取验证码
	 * @throws base_Exception
	 * @return string 验证码字符串
	 */
	public static function getCheckCode()
	{
	    $fontPath = CK_APPLICATION_DATA_DIR.'verdanaz.ttf';
	    if(!file::exists($fontPath))
	    {
	        throw new base_Exception(lang::getLang('__NOT_FOUND_CHECK_CODE_FONT_FILE__',array($fontPath)));    
	    }
		$img = imagecreatetruecolor(self::$width,self::$height);
		$checkCodeArr = array('q','w','e','r','t','y','u','o','i','p',
							  'a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m',
							  1,2,3,4,5,6,7,8,9,0);
	    $rangArr = array_rand($checkCodeArr,4);
	    imagefill($img,0,0,imagecolorallocate($img,rand(0xFA,0XCD), rand(0xFA,0XCD), 0XFD));
	    $x = 2;
	    $y = rand(16,28);
		$checkStr = '';
		$width = intval(self::$width / 4.5);
		$minWidth = $width ;
		$minHeight = 18;
		$maxHeight = self::$height - 4;
		foreach ($rangArr as $k)
		{
			$x1 = $x;
			$y1 = $y;
			$y = rand($minHeight,$maxHeight);
			$x += rand($minWidth,$width);
			if($x < 10)
			{
				$x = 14;
			}
			$checkStr .= $checkCodeArr[$k];
			for($i=0;$i<30;$i++)
			{
				imagesetpixel($img,rand($x-20,$x+5),rand($y-20,$y+5),imagecolorallocate($img,rand(0, 0XFF), rand(0, 0XFF), rand(0, 0XFF)));
			}
			$rand1 = rand(12,16);
			$rand2 = rand(-20, 40);
			imagettftext($img,$rand1,$rand2,$x-14,$y,imagecolorallocate($img, rand(0x0, 0x4F), rand(0xB3, 0x4A), rand(0x0, 0x9A)),CK_APPLICATION_DATA_DIR.'verdanaz.ttf',$checkCodeArr[$k]);
			imagettftext($img,$rand1,$rand2,$x-16,$y,imagecolorallocate($img, rand(0x0, 0x4F), rand(0xB3, 0x4A), rand(0x0, 0x9A)),CK_APPLICATION_DATA_DIR.'verdanaz.ttf',$checkCodeArr[$k]);
		}
		header("content-type:image/png\r\n");
		imagepng($img);
		imagedestroy($img);
		return $checkStr;
	}
}